package com.concurrent.frame.core;

import com.concurrent.frame.mark.ThreadSafe;
import com.concurrent.frame.pojo.JobInfo;
import com.concurrent.frame.processor.task.ITaskProcessor;
import com.concurrent.frame.util.Assert;

import java.util.Map;
import java.util.concurrent.*;
@ThreadSafe
public class ResourceRegisterPool {
    //有界队列:  任务阻塞队列
    private static BlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<Runnable>(5000);
    //线程池大小: CPU核心数
    private static final int THREAD_COUNTS = Runtime.getRuntime().availableProcessors();
    //生产者线程池
    private static ExecutorService taskExecutor = new ThreadPoolExecutor(THREAD_COUNTS,THREAD_COUNTS*2,60, TimeUnit.SECONDS, taskQueue);

    public static ExecutorService getTaskExecutor() {
        return taskExecutor;
    }

    //job的存放容器
    private static ConcurrentHashMap<String, JobInfo<?>> jonInfoMap = new ConcurrentHashMap<String, JobInfo<?>>();
    //延迟队列,保存处理结果一定时间
    private static CheckJobProcessor checkJobProcessor = CheckJobProcessor.getInstance();
    //单例模式
    private ResourceRegisterPool() {
    }
    private static class  JobPoolHolder{
        public static ResourceRegisterPool pool = new ResourceRegisterPool();
    }
    public static ResourceRegisterPool getIntance(){
        return  JobPoolHolder.pool;
    }

    //注册工作
    public <R> void registerJob(JobInfo jobInfo){
        if (jonInfoMap.putIfAbsent(jobInfo.getJobName(),jobInfo)!=null){//不会覆盖数据
            throw new RuntimeException(jobInfo.getJobName()+"已经注册了!");
        }
    }

    //提交工作任务
    public <T,R> void putTask(String jobName,T t){
        final JobInfo<R> jobInfo;
        try {
            jobInfo = getJob(jobName);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        ITaskProcessor taskProcessor = jobInfo.getTaskProcessor();
        taskProcessor.process(t);
    }
    @SuppressWarnings("unchecked")
    private <R> JobInfo<R> getJob(String jobName)throws Exception{
            Assert.isNotNULL(jobName,"是一个非法任务！");
            JobInfo<R> jobInfo = (JobInfo<R>) jonInfoMap.get(jobName);
            return jobInfo;
    }
    //获得工作的整体处理进度
    public <R> String getTaskProgess(String jobName) {
        JobInfo<R> jobInfo = null;
        try {
            jobInfo = getJob(jobName);
            return jobInfo.getTotalProcess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "查询失败！";
    }
    public static Map<String,JobInfo<?>> getMap(){
        return jonInfoMap;
    }

    public static CheckJobProcessor getCheckJobProcessor() {
        return checkJobProcessor;
    }
}
